from flask import Blueprint, request, jsonify, session, current_app, render_template
from sympy.logic.inference import valid
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, logout_user, current_user, login_required
from app.models import User, UserSettings
from app import db

bp = Blueprint('auth', __name__)


@bp.route('/register', methods=['POST'])  # 移除了GET方法
def register():
    try:
        data = request.get_json()

        # 验证输入
        if not data:
            return jsonify({'error': '请求体必须为JSON格式'}), 400

        required_fields = ['username', 'password']
        missing = [field for field in required_fields if field not in data]
        if missing:
            return jsonify({'error': f'缺少必填字段: {", ".join(missing)}'}), 400

        # 检查空值
        if not data['username'].strip() or not data['password'].strip():
            return jsonify({'error': '用户名和密码不能为空'}), 400

        # 检查用户是否存在
        if User.query.filter_by(username=data['username'].strip()).first():
            return jsonify({'error': '用户名已存在'}), 409  # 更合适的HTTP状态码

        # 检查邮箱(如果提供)
        if 'email' in data and data['email']:
            if User.query.filter_by(email=data['email'].strip()).first():
                return jsonify({'error': '邮箱已存在'}), 409
            email = data['email'].strip()
        else:
            email = None

        # 创建用户对象并设置属性
        user = User(
            username=data['username'].strip(),
            email=email
        )
        user.set_password(data['password'])  # 现在所有必要字段都已设置

        # 在一个事务中完成所有操作
        db.session.add(user)
        db.session.flush()  # 提交用户对象到数据库

        # 创建默认用户设置
        settings = UserSettings(
            user_id=user.id,  # 明确设置user_id
            max_tokens=2000,
            temperature=0.7
            # ...其他默认设置...
        )
        db.session.add(settings)

        db.session.commit()  # 单次提交

        return jsonify({
            'success': True,
            'user_id': user.id,
            'message': '注册成功'
        }), 201

    except Exception as e:
        db.session.rollback()
        # 生产环境应记录日志而不是返回错误详情
        current_app.logger.error(f'注册失败: {str(e)}', exc_info=True)
        return jsonify({'error': '注册失败，请稍后重试'}), 500


# 登录路由
@bp.route('/login-get', methods=['GET'])
def login_page():
    return render_template('auth.html')


@bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()

    if not data or not data.get('username') or not data.get('password'):
        return jsonify({'error': '用户名和密码是必填项'}), 400

    user = User.query.filter_by(username=data['username']).first()

    if not user or not user.check_password(data['password']):
        return jsonify({'error': '无效的用户名或密码'}), 401

    login_user(user)
    session['user_id'] = user.id
    return jsonify({
        'success': True,
        'user': {
            'id': user.id,
            'username': user.username
        }
    })


@bp.route('/logout', methods=['POST', 'GET'])
def logout():
    logout_user()
    session.pop('user_id', None)
    return jsonify({'success': True})


@bp.route('/check_auth', methods=['GET'])
def check_auth():
    if current_user.is_authenticated:
        return jsonify({
            'authenticated': True,
            'user_id': current_user.id,
            'username': current_user.username
        })
    return jsonify({'authenticated': False}), 401


@bp.route('/user/<user_id>', methods=['GET'])
@login_required
def get_user(user_id):
    print(user_id)
    print(current_user.id)
    if current_user.id != user_id:
        return jsonify({'error': '无权访问'}), 403

    user = User.query.get_or_404(user_id)
    return jsonify({
        'id': user.id,
        'username': user.username,
        'email': user.email,
        'created_at': user.created_at.isoformat()
    })
